package com.dorm.manage.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.dorm.common.core.domain.entity.DormBuilding;
import com.dorm.common.core.domain.entity.SysDept;
import com.dorm.manage.service.IDormBuildingService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.dorm.common.annotation.Log;
import com.dorm.common.core.controller.BaseController;
import com.dorm.common.core.domain.AjaxResult;
import com.dorm.common.enums.BusinessType;
import com.dorm.manage.domain.DormStudent;
import com.dorm.manage.service.IDormStudentService;
import com.dorm.common.utils.poi.ExcelUtil;
import com.dorm.common.core.page.TableDataInfo;

/**
 * 学生管理Controller
 * 
 * @author 王新瑜
 * @date 2025-06-04
 */
@RestController
@RequestMapping("/dorm/student")
public class DormStudentController extends BaseController
{
    @Autowired
    private IDormStudentService dormStudentService;

    @Autowired
    private IDormBuildingService dormBuildingService;

    /**
     * 查询学生管理列表
     */
    @PreAuthorize("@ss.hasPermi('dorm:student:list')")
    @GetMapping("/list")
    public TableDataInfo list(DormStudent dormStudent)
    {
        startPage();
        List<DormStudent> list = dormStudentService.selectDormStudentList(dormStudent);
        return getDataTable(list);
    }

    /**
     * 导出学生管理列表
     */
    @PreAuthorize("@ss.hasPermi('dorm:student:export')")
    @Log(title = "学生管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DormStudent dormStudent)
    {
        List<DormStudent> list = dormStudentService.selectDormStudentList(dormStudent);
        ExcelUtil<DormStudent> util = new ExcelUtil<DormStudent>(DormStudent.class);
        util.exportExcel(response, list, "学生管理数据");
    }

    /**
     * 获取学生管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('dorm:student:query')")
    @GetMapping(value = "/{studentId}")
    public AjaxResult getInfo(@PathVariable("studentId") Long studentId)
    {
        return success(dormStudentService.selectDormStudentByStudentId(studentId));
    }

    /**
     * 新增学生管理
     */
    @PreAuthorize("@ss.hasPermi('dorm:student:add')")
    @Log(title = "学生管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody DormStudent dormStudent)
    {
        try {
            return toAjax(dormStudentService.insertDormStudentWithCapacityCheck(dormStudent));
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

    /**
     * 修改学生管理
     */
    @PreAuthorize("@ss.hasPermi('dorm:student:edit')")
    @Log(title = "学生管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DormStudent dormStudent)
    {
        try {
            return toAjax(dormStudentService.updateDormStudentWithCapacityCheck(dormStudent));
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

    /**
     * 删除学生管理
     */
    @PreAuthorize("@ss.hasPermi('dorm:student:remove')")
    @Log(title = "学生管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{studentIds}")
    public AjaxResult remove(@PathVariable Long[] studentIds)
    {
        return toAjax(dormStudentService.deleteDormStudentByStudentIds(studentIds));
    }

    /**
     * 获取宿舍树列表
     */
    @PreAuthorize("@ss.hasPermi('dorm:student:list')")
    @GetMapping("/dormTree")
    public AjaxResult deptTree(DormBuilding dormBuilding)
    {
        return success(dormBuildingService.selectDormTreeList(dormBuilding));
    }

    /**
     * 获取带容量信息的宿舍树列表
     */
    @PreAuthorize("@ss.hasPermi('dorm:student:list')")
    @GetMapping("/dormTreeWithCapacity")
    public AjaxResult dormTreeWithCapacity(DormBuilding dormBuilding)
    {
        return success(dormBuildingService.selectDormTreeList(dormBuilding));
    }

    /**
     * 查询是否为学生账号
     */
    @GetMapping("/isStudent/{username}")
    public AjaxResult isStudent(@PathVariable("username") String username)
    {
        boolean isStudent = dormStudentService.isStudentByUserName(username);
        return success(isStudent);
    }

    /**
     * 根据用户名判断user_id是否存在
     */
    @GetMapping("/isStudentInfoFilled/{username}")
    public AjaxResult checkUserIdExists(@PathVariable("username") String username)
    {
        boolean exists = dormStudentService.isUserIdExistsByUserName(username);
        return success(exists);
    }

    /**
     * 根据用户名查询学生信息
     */
    @GetMapping("/getStudentInfo")
    public AjaxResult getStudentInfo()
    {
        DormStudent student = dormStudentService.selectDormStudentByUserId();
        return success(student);
    }

    /**
     * 用户端更新学生信息
     */
    @PutMapping("/updateStudentInfo")
    public AjaxResult updateStudentInfo(@RequestBody DormStudent dormStudent)
    {
        return toAjax(dormStudentService.UpdateDormStudentInfo(dormStudent));
    }

    /**
     * 获取学生统计数据
     */
    @GetMapping("/statistics")
    public AjaxResult getStudentStatistics()
    {
        try {
            Map<String, Object> statistics = new HashMap<>();

            // 获取所有学生数据
            List<DormStudent> allStudents = dormStudentService.selectDormStudentList(new DormStudent());

            // 统计总学生数
            int totalStudents = allStudents.size();

            // 统计在校学生数
            long inSchoolStudents = allStudents.stream()
                .filter(student -> "0".equals(student.getStatus()))
                .count();

            // 统计离校学生数
            long outSchoolStudents = allStudents.stream()
                .filter(student -> "1".equals(student.getStatus()))
                .count();

            // 统计男女学生数
            long maleStudents = allStudents.stream()
                .filter(student -> "0".equals(student.getGender()))
                .count();

            long femaleStudents = allStudents.stream()
                .filter(student -> "1".equals(student.getGender()))
                .count();

            // 统计已分配宿舍的学生数
            long assignedStudents = allStudents.stream()
                .filter(student -> student.getDormId() != null)
                .count();

            // 统计未分配宿舍的学生数
            long unassignedStudents = totalStudents - assignedStudents;

            statistics.put("totalStudents", totalStudents);
            statistics.put("inSchoolStudents", inSchoolStudents);
            statistics.put("outSchoolStudents", outSchoolStudents);
            statistics.put("maleStudents", maleStudents);
            statistics.put("femaleStudents", femaleStudents);
            statistics.put("assignedStudents", assignedStudents);
            statistics.put("unassignedStudents", unassignedStudents);

            return success(statistics);
        } catch (Exception e) {
            return error("获取学生统计数据失败：" + e.getMessage());
        }
    }
}
